package exp;

import utils.BasicJPanel;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;

public class GrayHistogramJPanel extends BasicJPanel
{

    private final JLabel imageJLabel;
    private final JLabel grayJLabel;
    private final JLabel histogramJLabel;
    private final JLabel histogram2JLabel;
    private final JLabel infoJLabel;


    public GrayHistogramJPanel()
    {
        super();
        setLayout(new BorderLayout());
                {
            JPanel jPanel=new JPanel();
            add(jPanel);
            jPanel.setLayout(new GridLayout(1,4));
            jPanel.add(imageJLabel=new JLabel());
            jPanel.add(grayJLabel=new JLabel());
            jPanel.add(histogramJLabel=new JLabel());
            jPanel.add(histogram2JLabel=new JLabel());
        }
        add(infoJLabel=new JLabel(),BorderLayout.NORTH);
    }

    public static BufferedImage getHistogramImage(int cntMaxI,int[] cnt)
    {
       return getHistogramImage(cntMaxI,cnt,cnt[cntMaxI]);
    }

    public static BufferedImage getHistogramImage(int cntMaxI,int[] cnt,int maxN)
    {
        final double r=300.0/maxN;
        final BufferedImage grayHistogram=new BufferedImage(256,300,BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<256;++i)
            for(int j=0;j<cnt[i]*r;++j)
                grayHistogram.setRGB(i,(grayHistogram.getHeight()-j-1),0XFF00FF00);
        return grayHistogram;
    }

    private void update()
    {
        final BufferedImage src=(BufferedImage)((ImageIcon)imageJLabel.getIcon()).getImage();
        final BufferedImage dst=new BufferedImage(src.getWidth(),src.getHeight(),BufferedImage.TYPE_INT_RGB);
        final int[] cnt=new int[256];
        for(int i=0;i<256;++i)
            cnt[i]=0;
        int cntMaxI=0;
        for(int i=0;i<src.getHeight();++i)
            for(int j=0;j<src.getWidth();++j)
            {
                final int t=GrayJPanel.RGBToGray(src.getRGB(j,i));
                ++cnt[t];
                if(cnt[t]>cnt[cntMaxI])
                    cntMaxI=t;
                dst.setRGB(j,i,GrayJPanel.grayToRGB(t));
            }
        infoJLabel.setText(String.format("最大频率@%d=%d %.2f%%",cntMaxI,cnt[cntMaxI],100.0*cnt[cntMaxI]/(src.getWidth()*src.getHeight())));

        grayJLabel.setIcon(new ImageIcon(dst));
        histogramJLabel.setIcon(new ImageIcon(getHistogramImage(cntMaxI,cnt)));
        histogram2JLabel.setIcon(new ImageIcon(getHistogramImage(cntMaxI,cnt,(src.getWidth()*src.getHeight()))));
    }

    public void update(Path path) throws IOException, BmpStructureErrorException
    {
        final Bmp bmp=new Bmp(path);
        imageJLabel.setIcon(new ImageIcon(bmp.getImage()));
        update();
    }


    public String getButtonName()
    {
        return "必做4:灰度直方图";
    }
}
